<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>扫码登录demo</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        let webSocket = null;

        $(function () {
            $.ajax({
                type: 'get',
                url: '/qrcode/init',
                dataType: 'json',
                success: function (resp) {
                    console.log(resp)
                    let ticket = resp.data.ticket;
                    let qr = resp.data.qr;
                    console.log(ticket);
                    console.log(qr);
                    $('#qr').attr('src', 'data:image/png;base64,' + qr)

                    //判断当前浏览器是否支持WebSocket
                    if ('WebSocket' in window) {
                        webSocket = new WebSocket("ws://localhost:9000/ws/qrcode/" + ticket);
                    } else {
                        console.log('webSocket not support')
                    }

                    //连接成功建立的回调方法
                    webSocket.onopen = function (event) {
                        setMessageInnerHTML("已连接");
                    };

                    //接收到消息的回调方法
                    webSocket.onmessage = function (event) {
                        setMessageInnerHTML(event.data);
                    };

                    //连接关闭的回调方法
                    webSocket.onclose = function () {
                        setMessageInnerHTML("已关闭");
                    };

                    //连接发生错误的回调方法
                    webSocket.onerror = function () {
                        setMessageInnerHTML("连接错误");
                    };
                }
            });
        });


        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            webSocket.close();
        };

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }

        //关闭连接
        function closeWebSocket() {
            webSocket.close();
        }

        const send = () => {
            let message = document.getElementById('text').value;
            webSocket.send(message);
        }


    </script>

</head>
<body>
<!--<h3>请输入要发送给客户端的消息：</h3><br/>-->

<!--<input id="text" type="text"/>-->
<!--<button onclick="send()">发送消息</button>-->

<button onclick="closeWebSocket()">关闭连接</button>

<br>连接信息:<br><span id="message"></span>

<br><br>
<img id="qr" src="" alt="扫码登录">

</body>
</html>